﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Web;
using TallComponents.Web.Storage;
using TallComponents.Web.Pdf.Services;
using TallComponents.PDF.Rasterizer.Configuration;

namespace TallComponents.Web.Pdf
{
   internal sealed class PlainPreviewGenerator : PreviewGenerator
   {

      /// <summary>
      /// Generates the preview.
      /// </summary>
      /// <param name="graphics">The graphics.</param>
      /// <param name="context">The context.</param>
      /// <param name="request">The request.</param>
      /// <param name="storage">The storage.</param>
      /// <param name="logger">The logger.</param>
      /// <param name="settings">The settings.</param>
      protected override void GeneratePreview(Graphics graphics, HttpContext context, PreviewRequesParameters request, IPdfStorage storage, ILog logger, RenderSettings settings)
      {
         Page page = storage.GetPage(request.Key, request.FirstPageIndex);

         // Ensure page is valid to prevent exceptions
         if (page == null)
         {
            graphics.Clear(Color.FromArgb(0, 0, 0, 0));
            return;
         }


         float zoom = request.ZoomPercentage;

         if (zoom <= 0)
         {
            float zoomx = (float)(request.Width / page.Width);
            float zoomy = (float)(request.Height / page.Height);
            zoom = Math.Min(zoomx, zoomy);
         }

         ApplyZoomTransformation(graphics, request, page);
         Matrix originalTx = graphics.Transform;

         for (int pageIndex = request.FirstPageIndex; pageIndex <= request.LastPageIndex; pageIndex++)
         {
            if (!context.Response.IsClientConnected)
               // No need to do anything else
               return;

            page = storage.GetPage(request.Key, pageIndex);

            //save before rotation
            Matrix transform = graphics.Transform;

            float dx = request.Locations[pageIndex - request.FirstPageIndex].X;
            float dy = request.Locations[pageIndex - request.FirstPageIndex].Y;

            graphics.TranslateTransform(dx, dy);
            ApplyRotationTransformation(graphics, page, request.Rotation[pageIndex - request.FirstPageIndex]);
            DrawPage(graphics, settings, page, logger);

            //restore after rotation
            graphics.Transform = transform;
         }
      }
   }
}
